﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Reflection;
using System.Text;
using System.Collections;

namespace DataObject.Core
{
    public class ObjectToTable
    {
        /// <summary>
        /// Convert IEnumerable to DataTable 
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static DataTable DataTableFromIEnumerable(IEnumerable collection)
        {
            DataTable dt = new DataTable();
            foreach (object obj in collection)
            {
                Type type = obj.GetType();
                PropertyInfo[] propertyInfos = type.GetProperties();
                if (dt.Columns.Count == 0)
                {
                    foreach (PropertyInfo pi in propertyInfos)
                    {
                        if (pi.Name.Contains("Error") || pi.Name == "Item") continue;
                        Type pt = pi.PropertyType;
                        if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
                            pt = Nullable.GetUnderlyingType(pt);
                        dt.Columns.Add(pi.Name, pt);
                    }
                }
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in propertyInfos)
                {
                    if (pi.Name.Contains("Error") || pi.Name == "Item") continue;
                    object value = pi.GetValue(obj, null);
                    dr[pi.Name] = value ?? DBNull.Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}
